package com.midongtech.cpd.utils;

import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {

    private static final String TAG = "HttpManager";
    public static final int TIME_OUT = 15000;

    public static void httpGet(String urlString, Map<String, String> paramsMap, final CommonCallBack callback) {
        StringBuilder builder = new StringBuilder();
        if (paramsMap != null) {
            for (String key : paramsMap.keySet()) {
                builder.append("&" + key + "=");
                builder.append(paramsMap.get(key));
            }
            String params = builder.toString();
            if (!urlString.contains("?")) {
                urlString += "?";
                if (params.startsWith("&")) {
                    params = params.substring(1, params.length() - 1);
                }
            }
            urlString += params;
        }
        final String finalUrlString = urlString;
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                InputStream in = null;
                StringBuffer strbuffer = null;
                BufferedReader reader = null;

                try {
                    final URL url = new URL(finalUrlString);
                    connection = (HttpURLConnection) url.openConnection();
//                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setReadTimeout(TIME_OUT);
                    connection.setConnectTimeout(TIME_OUT);
                    connection.setRequestMethod("GET");
                    connection.setUseCaches(false);
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    int responseCode = connection.getResponseCode();
//                    if (responseCode == 200) {
                    in = connection.getInputStream();
                    if (null == in) {
                        if (callback != null) {
                            callback.onFailure("response null");
                        }
                        return;
                    }
                    strbuffer = new StringBuffer();
                    String line;
                    reader = new BufferedReader(new InputStreamReader(in));
                    while ((line = reader.readLine()) != null) {
                        strbuffer.append(line).append("\r\n");
                    }
                    String msg = strbuffer.toString();
                    Log.i(TAG,finalUrlString + "   responseMsg:" + msg);
                    if (callback != null) {
                        callback.onSuccess(msg);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onFailure(e.getMessage());
                    }

                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (final IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    public static void httpPost(final String urlString, Map<String, String> paramsMap,  final CommonCallBack callback) {
        StringBuilder builder = new StringBuilder();
        for (String key : paramsMap.keySet()) {
            builder.append("&" + key + "=");
            builder.append(paramsMap.get(key));
        }
        String params = builder.toString();
        if (!TextUtils.isEmpty(params) && params.startsWith("&")) {
            params = params.substring(1);//去掉&字符
        }

        final String paramsResult = params;
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                InputStream in = null;
                StringBuffer strbuffer = null;
                BufferedReader reader = null;

                try {
                    final URL url = new URL(urlString);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setReadTimeout(TIME_OUT);
                    connection.setConnectTimeout(TIME_OUT);
                    connection.setRequestMethod("POST");
                    connection.setUseCaches(false);
                    //设置请求属性
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
                    connection.setRequestProperty("Charset", "UTF-8");
                    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
                    dos.writeBytes(paramsResult);
                    dos.flush();
                    dos.close();
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200) {
                        in = connection.getInputStream();
                        if (null == in) {
                            if (callback != null) {
                                callback.onFailure("response null");
                            }
                            return;
                        }
                        strbuffer = new StringBuffer();
                        String line;
                        reader = new BufferedReader(new InputStreamReader(in));
                        while ((line = reader.readLine()) != null) {
                            strbuffer.append(line).append("\r\n");
                        }
                        String msg = strbuffer.toString();
                        Log.i(TAG, urlString + "   responseMsg:" + msg);
                        if (callback != null) {
                            callback.onSuccess(msg);
                        }
                    } else {
                        if (callback != null) {
                            callback.onFailure(responseCode + "");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onFailure(e.getMessage());
                    }
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (final IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }



}
